package cn.edu.lingnan.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;

import cn.edu.lingnan.model.User;

public class registDao {
	
	//2019
	public boolean findByName(String userName) throws ClassNotFoundException {
		boolean flag=false;
		Connection conn=null;
		PreparedStatement prep = null;
		ResultSet rs=null;//还没关闭，不可再用
		try {
			 Class.forName("com.mysql.jdbc.Driver");//1
	           conn=DriverManager.getConnection
	                    ("jdbc:mysql://localhost:3306/SharingCarRental","root","system12");//2
	        //假设用户已存在返回1
			prep=conn.prepareStatement("select * from t_user where userName=?");
			prep.setString(1, userName);
			rs=prep.executeQuery();//结果集
			if(rs.next()) {
				flag = true;
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				if(rs!=null) {
					rs.close();
					rs=null;
				}
				if(prep!=null) {
					prep.close();
					prep=null;
				}
				if(conn!=null) {
					conn.close();
					conn=null;
				}
			}catch(SQLException e) {
				e.printStackTrace();
			}
		}
		return flag;
	}
		
		
		//插入一个学生信息
		public int insertInfoToUser(User s) throws ClassNotFoundException{
			int flag=0;
			String id= s.getId();
			String userName = s.getUserName();
			String password = s.getPassword();
			String sSuper = s.getSspur();
			Connection conn=null;
			PreparedStatement prep = null;
			PreparedStatement prep1 = null;
			ResultSet rs1=null;//还没关闭，不可再用
			int rs=0;
			try {
				 Class.forName("com.mysql.jdbc.Driver");//1
		           conn=DriverManager.getConnection
		                    ("jdbc:mysql://localhost:3306/SharingCarRental","root","system12");//2
		        //假设用户已存在返回1
				prep1=conn.prepareStatement("select * from t_user where userName=?");
				prep1.setString(1, userName);
				rs1=prep1.executeQuery();//结果集
				while(rs1.next()) {
					System.out.println("该用户已存在！");
					System.out.println();
				}
				
				//当用户没有重复的情况下执行插入操作
				prep=conn.prepareStatement("insert into t_user values (?,?,?,?)");
			    prep.setString(1, id);
				prep.setString(2, userName);
				prep.setString(3, password);
				prep.setString(4, sSuper);
				rs=prep.executeUpdate();
				if(rs==0) {
					System.out.println("插入失败！");
					System.out.println();
					flag = 2;
				}
				else {
					System.out.println("插入成功！");
					System.out.println();
				}
			}catch(SQLException e) {
				e.printStackTrace();
			}finally {
				try {
					if(rs1!=null) {
						rs1.close();
						rs1=null;
					}
					if(prep!=null) {
						prep.close();
						prep=null;
					}
					if(prep1!=null) {
						prep1.close();
						prep1=null;
					}
					if(conn!=null) {
						conn.close();
						conn=null;
					}
				}catch(SQLException e) {
					e.printStackTrace();
				}
			}
			return flag;
		}
		

}
